package com.example.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.example.common.api.ApiResult;
import com.example.entity.emp.SysPermission;
import com.example.service.SysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "权限管理接口")
@RestController
@RequestMapping("/permission")
@RequiredArgsConstructor
public class SysPermissionController {

    private final SysPermissionService permissionService;

    @GetMapping("/tree")
    @ApiOperation("获取权限树形列表")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<List<SysPermission>> tree() {
        return ApiResult.success(permissionService.getPermissionTree());
    }

    @PostMapping
    @ApiOperation("新增权限")
//    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> add(@Validated @RequestBody SysPermission permission) {
        permissionService.add(permission);
        return ApiResult.success();
    }

    @PutMapping
    @ApiOperation("修改权限")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> update(@Validated @RequestBody SysPermission permission) {
        permissionService.update(permission);
        return ApiResult.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除权限")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> delete(@PathVariable Long id) {
        permissionService.delete(id);
        return ApiResult.success();
    }

    @GetMapping("/role/{roleId}")
    @ApiOperation("获取角色的权限ID列表")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<List<Long>> getRolePermissionIds(@PathVariable Long roleId) {
        return ApiResult.success(permissionService.getRolePermissionIds(roleId));
    }

    @GetMapping("/user")
    @ApiOperation("获取当前用户的权限列表")
    public ApiResult<List<SysPermission>> getCurrentUserPermissions() {
        Long userId = Long.valueOf(cn.dev33.satoken.stp.StpUtil.getLoginIdAsString());
        return ApiResult.success(permissionService.getUserPermissions(userId));
    }

    /**
     * 获取所有权限列表（平铺结构）
     */
    @GetMapping("/list")
    @ApiOperation("获取所有权限列表")
    public ApiResult<List<SysPermission>> list() {
        List<SysPermission> list = permissionService.list();
        return ApiResult.success(list);
    }
} 